#include "StdAfx.h"
#include "MediawikiXmlReader.h"

CMediawikiXmlReader::CMediawikiXmlReader(QObject *parent)
	: QXmlDefaultHandler(),m_errorOccurred(false),m_readingText(false)

{

}

CMediawikiXmlReader::~CMediawikiXmlReader()
{

}

bool CMediawikiXmlReader::startElement( const QString& namespaceURI, const QString& localName, const QString& qName, const QXmlAttributes& atts )
{
	if (qName == "page")
	{
		// Get the page name
		m_pageName = atts.value("title");
		m_editToken = atts.value("edittoken");
	}
	else if (qName == "rev")
	{
		// Get the user
		m_user = atts.value("user");
		m_rollbackToken = atts.value("rollbacktoken");
	}
	else if (qName == "error")
	{
		qDebug("MediaWiki API Error: %s: %s", atts.value("code"), atts.value("info"));
		m_errorOccurred = true;
		m_error = atts.value("info");
		m_errorCode = atts.value("code");
	}
	else if (qName == "login")
	{
		// Check the result, classify non-success as error
		QString result = atts.value("result");
		m_errorOccurred = (result != "Success");
		if (m_errorOccurred)
		{
			m_error = "Login failed or incorrect password specified [" + atts.value("result") + "]";
			m_errorCode = result;

			if (result == "NeedToken")
			{
				m_loginToken = atts.value("token");
			}
		}
	}
	else if (qName == "text")
	{
		m_readingText = true;
	}

	return true;
}

bool CMediawikiXmlReader::endElement( const QString & namespaceURI, const QString & localName, const QString & qName )
{
	if (qName == "text")
		m_readingText = false;

	return true;
}

bool CMediawikiXmlReader::characters( const QString& ch )
{
	if (m_readingText)
		m_text += ch;

	return true;
}